var express = require('express');
var router = express.Router();
var userDAO = require("../bin/userDAO.js");
var md5 = require("md5");

// 判断是否登录接口
var reqFilter = require("../bin/reqFilter");

var multer = require("multer");

// 用户头像上传
var useravatar = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/img/avatar')
  },
  filename: function (req, file, cb) {
    var suffix = file.mimetype.split("/")[1];
    var filename = file.fieldname + '-' + req.session.user._id+"."+suffix;
    req.avatar = "http://localhost:3000/img/avatar/"+filename;
    cb(null, filename);    
  }
})
var useravatar = multer({ storage: useravatar })

/* GET home page. */
// 用户注册
router.post("/regist",(req,res)=>{
  // console.log(req.body);
  userDAO.findOne({username:req.body.username})
  .then(data=>{
    if(data){
      res.json({err:1,msg:"用户名已被占用"});
    }else{
      if(req.body.psw!=req.body.confirm){
        res.json({err:2,msg:"两次密码输入不一致"})
      }else{
        req.body.psw = md5(req.body.psw);
        var u = new userDAO(req.body);
        u.save()
        .then(data=>{
          res.json({err:0,msg:"注册成功"})
        })
      }
    }
  })
})


// 用户登录
router.post("/login",(req,res)=>{
  userDAO.findOne({username:req.body.username})
  .then(data=>{
    if(!data){
      res.json({err:1,msg:"此用户名不存在"})
    }else{
      data.psw = md5(req.body.psw);
      // console.log(data.psw);
      if(data.psw!=md5(req.body.psw)){
        res.json({err:2,msg:"密码错误"})
      }else{
        req.session.user = data;
        res.json({err:0,msg:"登陆成功"})
      }
      
    }
  })
})

// 判断用户是否登录
router.post("/islogin",(req,res)=>{
  if(!req.session.user){
    res.json({err:1,msg:"请先登录"});
  }else{
    res.json({err:0,userInfo:req.session.user});
  }
})


// 用户上传头像
router.post("/userupload",reqFilter);
router.post("/userupload",useravatar.single("avatar"),(req,res)=>{
  // console.log(req.body);
  userDAO.findOne({username:req.session.user.username})
  .then(data=>{
    // console.log(data);
    data.avatar = req.avatar;
    data.save()
    .then(data1=>{
      res.json({err:0,msg:"上传成功"});
    })
  })
})
// 用户头像请求接口
router.post("/useravatar",(req,res)=>{
   userDAO.findOne({username:req.session.user.username})
   .then(data=>{
     res.json({err:0,data});
   })
});


// 添加我的看房团
router.post("/visitive",(req,res)=>{
  userDAO.findOne({username:req.body.username})
  .then(data=>{
    data.myvisitive.push(req.body.visitive);
    data.save()
    .then(data1=>{
      console.log(data1);
      res.json({err:0,msg:"添加成功"});
    })
  })
  


})
// 退出登录
router.post("/logout",(req,res)=>{
  req.session.user = null;
  res.json({err:0,msg:"退出成功"});
})
module.exports = router;
